import { AxiosResponse } from 'axios'
import { refreshToken } from '@/api/user/admin-login'
import router from '@/router'

import { setToken, clearToken } from '@/utils/common/auth'

let updateTokenTag = true,
  requestArr: any[] = []

/**
 * 刷新token
 * @param response
 * @param axios
 * @returns
 */
export const refreshTokenHandle = async (
  response: AxiosResponse,
  axios: any
) => {
  const config = response.config
  if (updateTokenTag) {
    console.log('正在刷新短token')
    updateTokenTag = false
    const config = response.config
    //获取刷新token
    const token = localStorage.getItem('refreshToken') as string
    try {
      //刷新token
      const res = await refreshToken(token)
      if (res.code === 200) {
        //设置token
        setToken(res.data.accessToken, res.data.refreshToken)
        // 执行完更新操作,重新执行未执行请求
        requestArr.forEach((execute) => execute())
        // 置空队列数组
        requestArr = []
        config.headers['satoken'] = res.data.accessToken

        console.log('token刷新成功')

        return axios(config)
      } else {
        console.log('token刷新失败')
        requestArr = []
        clearToken()
        router.push('/cvmagic/login')
      }
      // 这里是第一次执行进入更新token的接口继续往下执行
    } catch {
      clearToken()
      router.push('/cvmagic/login')
    } finally {
      updateTokenTag = true
    }
  } else {
    // 通过异步将并行的接口加入队列中，等上面更新完token接口再执行队列
    return new Promise((resolve) => {
      // 用函数的方式将相应数据resolve出去，执行函数就能得到响应结果
      requestArr.push(() => {
        return resolve(axios(config))
      })
    })
  }
  return response
}
